import Vue from "vue";
import VueRouter from "vue-router";
import Index from "../views/index.vue";
import store from '../store/index'
//处理重定向抛出异常的问题
const a = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
    return a.call(this, location).catch(err => err);
}
Vue.use(VueRouter);

const routes = [{
        path: "/",
        name: "Index",
        component: Index,
    },
    {
        path: "/category",
        name: "Category",
        component: () =>
            import ("@/views/Category"),
    },
    {
        path: "/cart",
        name: "Cart",
        meta: { needLogin: true },
        component: () =>
            import ("@/views/Cart"),
    },
    {
        path: "/my",
        name: "My",
        meta: { needLogin: true },
        component: () =>
            import ("@/views/My"),
    },
    {
        path: '/login',
        name: 'Login',
        component: () =>
            import ('../views/Login')
    },
    {
        path: '/hot_new_goods',
        name: 'HotNewGoods',
        component: () =>
            import ('../views/HotNewGoods.vue')
    }
];

const router = new VueRouter({
    mode: "history",
    routes,
});
//设置全局路由守卫，监控一些路由跳转是否需要登录后才能跳转
router.beforeEach((to, from, next) => { //全局路由守卫.
    console.log('needLogin', to.meta.needLogin);
    console.log('isLogin==>', store.getters['isLogin']);
    //to.meta.needLogin 有值代表需要登录，为true  isLogin 没有登录返回false
    if (to.meta.needLogin && !store.getters['isLogin']) {
        //to去到的目标路由是需要登陆的但用户却没有登录，那么就跳转到用户登录页面
        console.log("发现没有登陆，要跳转到登录页面啦！");
        next('/login');
        return;
    }
    //否则就可以正常跳转
    next();
});
export default router;